﻿using LinqToDB.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PMS.Core.Infrastructure;
using PMS.Data.DbUtils;

namespace PMS.Web.Framework.StartupCfgs.StartupSetups
{
    /// <summary>
    /// Represents object for the configuring DB context on application startup
    /// </summary>
    public class DbStartup : IPMSStartup
    {
        /// <summary>
        /// Add and configure any of the middleware
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //https://github.com/dotnet/efcore/issues/9417 使用数据库连接池时不能在DbContext中设置UseQueryTrackingBehavior
            services.AddDbContextPool<AppDbContext>(optionsBuilder =>
            {
                optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()));
                optionsBuilder.UseDatabaseWithLazyLoading(services);
                optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll);
            });
            //Add Linq2db EntityFramework support
            LinqToDBForEFTools.Initialize();
            services.AddEntityFrameworkProxies();
        }

        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application)
        {
        }

        /// <summary>
        /// Gets order of this startup configuration implementation
        /// </summary>
        public int Order => StartupOrderConfig.DbStartOrder;
    }

}
